//pages/[category]/[refinement]/index.tsx
import React, { useMemo } from "react";
import { useProducts } from "@/business.InterfaceLayer/hooks/store/useQueryStore/useQueryStore";
import { useRouter } from "next/router";
import useProductData from "@/business.InterfaceLayer/hooks/useProductData";
import useSortFilters from "@/business.InterfaceLayer/hooks/useSortFiltersQuery";
import useFilterProducts from "@/business.InterfaceLayer/hooks/useFilterProducts";
import { Product } from "@/business.InterfaceLayer/type";
import MainLayout from "@/user.InterfaceLayer/Libraries/Layouts/Main.layout";

const RefinementPage: React.FC = () => {
  const router = useRouter();
  const { category, refinement } = router.query;
  const { products: allProducts, isLoading } = useProducts();

  // Фильтрация продуктов по категории и подкатегории
  const filteredByCategoryAndRefinement = useMemo(() => {
    if (!allProducts || !category || !refinement) return [];
    return allProducts.filter(
      (product: Product) =>
        product.category === category && product.refinement === refinement
    );
  }, [allProducts, category, refinement]);

  const { uniqueBrands, uniqueColors, maxPrice } = useProductData(
    filteredByCategoryAndRefinement
  );
  const { filters, applyFilters, clearFilters } = useSortFilters();
  const filteredProducts = useFilterProducts(filteredByCategoryAndRefinement);

  // if (
  //   !category ||
  //   !refinement ||
  //   filteredByCategoryAndRefinement.length === 0
  // ) {
  //   return <Page404 />;
  // }

  return (
    <MainLayout
      isLoading={isLoading}
      uniqueBrands={uniqueBrands}
      uniqueColors={uniqueColors}
      maxPrice={maxPrice}
      filters={filters}
      applyFilters={applyFilters}
      clearFilters={clearFilters}
      filteredProducts={filteredProducts}
    />
  );
};
export default RefinementPage;
